extends Control
class_name BattleCommandPanel

@onready var label: Label = $Info/Label
@onready var selectArrow: TextureRect = $SelectArrowParent/SelectArrow
@onready var info: NinePatchRect = $Info

var arrowMinY = 0
var arrowMaxY = 0
var stepLength = 16
var lines = 0
var padding = 19
var options = []

signal onSelectResult

func _ready() -> void:
	if label.text.strip_edges() != "":
		calcArrowMinMaxY()
	hide()


func setPos(pos):
	position = pos
	

func setWidth(width):
	info.size.x = width


func calcArrowMinMaxY():
	arrowMaxY = (lines - 1) * stepLength
	arrowMinY = 0
	
	
func showPanel():
	call_deferred("show")
	selectArrow.position.y = 0


func setOption(str):
	label.text = str
	options = label.text.split("\n")
	lines = options.size()
	calcArrowMinMaxY()
	updateContainerHeight()
	

func _physics_process(delta: float) -> void:
	processArrowMove()
	processSelect()
		
		
func processArrowMove():
	if Input.is_action_just_pressed("MoveDown"):
		var targetY = selectArrow.position.y + stepLength
		targetY = clamp(targetY, arrowMinY, arrowMaxY)
		selectArrow.position.y = targetY
	
	if Input.is_action_just_pressed("MoveUp"):
		var targetY = selectArrow.position.y - stepLength
		targetY = clamp(targetY, arrowMinY, arrowMaxY)
		selectArrow.position.y = targetY
		
	
func processSelect():
	if not visible: return
	
	if Input.is_action_just_pressed("Confirm"):
		var index = selectArrow.position.y / stepLength
		onSelectResult.emit(index, options[index])
		

func updateContainerHeight():
	info.size.y = padding + (label.label_settings.font_size * lines + label.label_settings.line_spacing * (lines - 1))
	
